﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Nirvana
{
    [CustomPropertyDrawer(typeof(EventNameAttribute))]
    public sealed class EventNamePropertyDrawer : PropertyDrawer
    {
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            return 1f * EditorGUIUtility.singleLineHeight;
        }

        public override void OnGUI(Rect pos, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(pos, label, property);
            UIEventBind uivariableBind = (UIEventBind)property.serializedObject.targetObject;
            if (uivariableBind != null)
            {
                var variableTable = uivariableBind.EventTable;
                if (variableTable != null)
                {
                    string[] events = variableTable.Events;
                    if (events != null)
                    {
                        this.DrawVariable(pos, property, label, variableTable);
                    }
                    else
                    {
                        GUI.enabled = false;
                        EditorGUI.PropertyField(pos, property);
                        GUI.enabled = true;
                    }
                }
                else
                {
                    GUI.enabled = false;
                    EditorGUI.PropertyField(pos, property);
                    GUI.enabled = true;
                }
            }
            else
            {
                GUI.enabled = false;
                EditorGUI.PropertyField(pos, property);
                GUI.enabled = true;
            }
            EditorGUI.EndProperty();
        }

        private void DrawVariable(Rect pos, SerializedProperty property, GUIContent label, UIEventTable eventTable)
        {
            Rect rect = new Rect(pos.x, pos.y, pos.width * 0.39f, pos.height);
            Rect rect2 = new Rect(pos.x + pos.width * 0.39f, pos.y, pos.width * 0.61f, pos.height);
            EditorGUI.PrefixLabel(rect, GUIUtility.GetControlID(FocusType.Passive), label);
            string[] events = eventTable.Events;
            if (events != null)
            {
                string[] array = new string[events.Length + 1];
                Array.Copy(events, array, events.Length);
                array[events.Length] = "None";
                int num = Array.FindIndex<string>(events,(p)=> p == property.stringValue );
                int num2 = EditorGUI.Popup(rect2, num, array);
                if (num2 != num && num2 >= 0)
                {
                    if (num2 < array.Length - 1)
                    {
                        property.stringValue = array[num2];
                    }
                    else
                    {
                        property.stringValue = string.Empty;
                    }
                }
            }

        }

    }
}

